package com.gagakuai.web.encript.core;

import com.gagakuai.web.encript.annonation.GagakuaiDecript;
import com.gagakuai.web.encript.config.GagakuaiEncryptProperties;
import com.gagakuai.web.encript.utils.AESUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

/*
 * @program: settement
 * @description:
 * @author: houhong
 * @create: 2022-11-19 11:00
 */
@ControllerAdvice
@EnableConfigurationProperties(GagakuaiEncryptProperties.class)
public class DecryptRequest extends RequestBodyAdviceAdapter {

    private Logger logger = LoggerFactory.getLogger(DecryptRequest.class);

    @Autowired
    private GagakuaiEncryptProperties properties;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {

        if (!methodParameter.hasMethodAnnotation(GagakuaiDecript.class)) {
            return false;
        }
        GagakuaiDecript gagakuaiDecript = methodParameter.getMethodAnnotation(GagakuaiDecript.class);
        return gagakuaiDecript.enabled();
    }

    @Override
    public HttpInputMessage beforeBodyRead(final HttpInputMessage inputMessage,
                                           MethodParameter parameter,
                                           Type targetType,
                                           Class<? extends HttpMessageConverter<?>> converterType) throws IOException {

        byte[] body = new byte[inputMessage.getBody().available()];
        inputMessage.getBody().read(body);

        try {
            byte[] decrypt = null; //AESUtils.decrypt(body, properties.getKey().getBytes());
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decrypt);
            return new HttpInputMessage() {
                @Override
                public HttpHeaders getHeaders() {
                    return inputMessage.getHeaders();
                }

                @Override
                public InputStream getBody() throws IOException {
                    return byteArrayInputStream;
                }
            };
        } catch (Exception e) {
            logger.error("gagakuai descprit error:{}", e);
        } finally {
        }

        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
    }
}